import { ErrorCode } from "../error/ErrorCode";
import { SLogin } from "../../../Message/Login/SLogin";
import { AMI_ILogin_login } from "../../../Message/Login/AMI_ILogin_login";
import { SMyRole } from "../../../Message/Login/SMyRole";
import { LoginRMI } from "../../game/net/rmi/login/LoginRMI";
import { GameSession } from "../../game/net/rmi/login/GameSession";
import { Log } from "../../../com/gengine/debug/Log";
import { SLoginReturn } from "../../../Message/Login/SLoginReturn";
import { ParamsConst } from "../global/ParamsConst";
import { EPublicCommand } from "../../../Message/Command/EPublicCommand";
import { PHPSender } from "../../../extend/php/PHPSender";
import { SUrl } from "../../../Message/Public/SUrl";
import { SenderType } from "../../../extend/php/SenderType";
import { Exception } from "../../../Framework/Util/Exception";
import { NetDispatcher } from "../../mvc/core/NetDispatcher";
import { MessageBlock } from "../../../Framework/MQ/MessageBlock";
import { SLoginInfoShow } from "../../../Message/Public/SLoginInfoShow";
import { SFirstRole } from "../../../Message/Login/SFirstRole";
import { ECareer } from "../../../Message/Public/ECareer";
import { AMI_ILogin_createFirstRole } from "../../../Message/Login/AMI_ILogin_createFirstRole";
import { EventDispatcher } from "../../../flash/events";
import { PreloaderCache } from "./PreloaderCache";
import { Global } from "../../../com/gengine/global/Global";
import { Event } from "../../../flash/events";

// did
export class PreLoginProxy extends EventDispatcher {
  constructor() {
    
    super();if (PreLoginProxy._instance) {
      throw new Error("单例！");
    }
    ErrorCode.init();
  }

  private showErrorInfo(arg1: Exception): void {
    if (Global.isDebugModle) {
      console.error("错误码：" + arg1.code + "\n错误信息：" + arg1.message);
    }
  }
  public doEnterGame(arg1: SMyRole): void {
    this._slogin.playerId = arg1.playerId;
    LoginRMI.instance.loginProxy.login_async(
      new AMI_ILogin_login(
        this.loginSuccess.bind(this),
        this.loginException.bind(this)
      ),
      this._slogin
    );
  }

  public doSetMain(arg1: SMyRole): void {
    this._slogin.playerId = arg1.playerId;
    this._slogin.setIsMain = 1;
    LoginRMI.instance.loginProxy.login_async(
      new AMI_ILogin_login(
        this.loginSuccess.bind(this),
        this.loginException.bind(this)
      ),
      this._slogin
    );
  }

  public login(): void {
    this._gameSession = new GameSession();
    this._gameSession.loginSession.url = ParamsConst.instance.loginIP;
    LoginRMI.instance.rmiSession = this._gameSession.loginSession;
    Log.debug("登陆服务器：" + this._gameSession.loginSession.url);
    this._slogin = new SLogin();
    this._slogin.username = ParamsConst.instance.username;
    this._slogin.userId = ParamsConst.instance.userId;
    this._slogin.server = ParamsConst.instance.server;
    this._slogin.time = ParamsConst.instance.time as Date;
    this._slogin.flag = ParamsConst.instance.flag;
    this._slogin.country = ParamsConst.instance.defaultCamp;
    this._slogin.isAdult = ParamsConst.instance.isAdult;
    this._slogin.codeVersion = ParamsConst.Version;
    this._slogin.platformCode = ParamsConst.instance.platformCode;
    this._slogin.password = ParamsConst.instance.password;
    this._slogin.loginIp = ParamsConst.instance.loginIP;
    this._slogin.totalOnlineTime = ParamsConst.instance.totalOnlineTime;
    this._slogin.platformUserName = ParamsConst.instance.platformUserName;
    this._slogin.issm = ParamsConst.instance.issm;
    this._slogin.gateIp = ParamsConst.instance.gameIP;
    NetDispatcher.addCmdListener(
      EPublicCommand._ECmdPublicLoginInfoShow,
      this.onShowLoginInfo
    );
    if (PHPSender.isCreateRole) {
      PHPSender.sendToURLByPHP(SenderType.Login);
    }
    LoginRMI.instance.loginProxy.login_async(
      new AMI_ILogin_login(
        this.loginSuccess.bind(this),
        this.loginException.bind(this)
      ),
      this._slogin
    );
  }

  public static get instance(): PreLoginProxy {
    if (!PreLoginProxy._instance) {
      PreLoginProxy._instance = new PreLoginProxy();
    }
    return PreLoginProxy._instance;
  }

  public loginSuccess(
    arg1: Object,
    arg2: SLoginReturn,
    roles?: Array<SMyRole>
  ): void {
    if (roles && roles.length > 0) {
      PreloaderCache.isMultipleRole = true;
      PreloaderCache.myRoles = roles;
      // this.initApp();
      this.doSetMain(roles[0]);
    } else {
      if (
        this._gameSession.loginSession &&
        this._gameSession.loginSession.session
      ) {
        this._gameSession.loginSession.session.abandon();
      }
      this._gameSession.gmaeSession.url = arg2.urls[0].url;
      Log.debug("登陆游戏服务器：" + this._gameSession.gmaeSession.url);
      this.sloginReturn = arg2;
      // this.removeCreateRole();
      // if (GameLoadBar.instance && !GameLoadBar.instance.visible) {
      //   GameLoadBar.instance.visible = true;
      // }
      if (PHPSender.isCreateRole) {
        PHPSender.sendToURLByPHP(SenderType.CreateRoleSuccess);
      }
      PHPSender.renrenAttention();
      this.isLoginSuccess = true;
      this.dispatchEvent(new Event(PreLoginProxy.LOGIN_SUCCESS));
      if (!PreloaderCache.isMultipleRole) {
        this.initApp();
      }
    }
    return;
  }

  public createRoleException(arg1: Exception): void {
    var loc1 = ErrorCode.getErrorByLogin(arg1.code);
    if (this._createRole && this._createRole.parent) {
      this._createRole.showException(loc1, arg1.code);
    } else if (!this.isLoginSuccess) {
      this.showErrorInfo(arg1);
    }
    PHPSender.sendToURLByPHP(SenderType.CreateRoleFail, arg1.message);
    return;
  }

  public loginException(arg1: Exception): void {
    if (arg1.code != ErrorCode.ErrorLogin_NoRole) {
      if (!this.isLoginSuccess) {
        this.showErrorInfo(arg1);
      }
      if (PHPSender.isCreateRole) {
        PHPSender.sendToURLByPHP(
          SenderType.LoginFail,
          "错误码：" + arg1.code + "\n错误信息：" + arg1.message
        );
      }
    } else {
      PHPSender.isCreateRole = true;
      this.createRole();
    }
    return;
  }

  public createRole(): void {
    this.onRoleCompleteHandler();
    // var loc1 = new Object /* flash.display.Loader */();
    // loc1.contentLoaderInfo.addEventListener(
    //   flash.events.Event.COMPLETE,
    //   this.onRoleCompleteHandler
    // );
    // loc1.contentLoaderInfo.addEventListener(
    //   flash.events.ProgressEvent.PROGRESS,
    //   this.onRoleProgressHandler
    // );
    // loc1.contentLoaderInfo.addEventListener(
    //   flash.events.IOErrorEvent.IO_ERROR,
    //   this.onLoadRoleHandler
    // );
    // loc1.load(new Object(/* flash.net.URLRequest */ PathConst.createRoleUrl));
    // PHPSender.sendToURLByPHP(SenderType.LoadCreateRole);
    return;
  }

  /**
   * 创建角色
   */
  private onRoleCompleteHandler(): // arg1: Object /* flash.events.Event */
  void {
    // if (GameLoadBar.instance && GameLoadBar.instance.visible) {
    //   GameLoadBar.instance.visible = false;
    // }
    // var loc1 = arg1.target as Object /* flash.display.LoaderInfo */;
    // loc1.removeEventListener(
    //   flash.events.Event.COMPLETE,
    //   this.onRoleCompleteHandler
    // );
    // loc1.removeEventListener(
    //   flash.events.ProgressEvent.PROGRESS,
    //   this.onRoleProgressHandler
    // );
    // loc1.removeEventListener(
    //   flash.events.IOErrorEvent.IO_ERROR,
    //   this.onLoadRoleHandler
    // );
    // this._createRole = loc1.content as Object /* flash.display.MovieClip */;
    // this._createRole.mainPath = ParamsConst.instance.mainPath;
    // this._createRole.version = ParamsConst.Version;
    // this._createRole.randomNameUrl = ParamsConst.instance.randomNameUrl;
    // if (this._createRole.hasOwnProperty("isAutoEnterGame")) {
    //   this._createRole.isAutoEnterGame = ParamsConst.instance.isAutoEnterGame;
    // }
    // this.rootStage.addChild(this._createRole);
    // this._createRole.setDefaultParams(
    //   ParamsConst.instance.roleName,
    //   ParamsConst.instance.defaultSex,
    //   ParamsConst.instance.defaultCamp
    // );
    // this._createRole.submitFun = this.submitFun;
    // if (this._createRole.hasOwnProperty("whoPlayGame")) {
    //   this._createRole.whoPlayGame(
    //     ParamsConst.instance.friendPlayGameUrl,
    //     ParamsConst.instance.whoPlayGameUrl
    //   );
    // }
    // this.rootStage.addEventListener(
    //   flash.events.MouseEvent.CLICK,
    //   this.onCreateRoleClickHandler
    // );
    PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleSuccess);
    this.initApp();
  }

  private onLoadRoleHandler(arg1: any /* flash.events.ErrorEvent */): void {
    PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleFail, arg1.text);
  }

  private onCreateRoleClickHandler(
    arg1: any /* flash.events.MouseEvent */
  ): void {
    PHPSender.sendToURLByPHP(SenderType.ClickCreateRole);
    // this.rootStage.removeEventListener(
    //   flash.events.MouseEvent.CLICK,
    //   this.onCreateRoleClickHandler
    // );
    return;
  }

  public onShowLoginInfo(arg1: MessageBlock): void {
    var loc1 = arg1.messageBase as SLoginInfoShow;
    if (this._createRole && this._createRole.parent) {
      this._createRole.addShowInfo(loc1.camp, loc1.sex, loc1.name);
    }
    return;
  }

  private removeCreateRole(): void {
    // if (this._createRole && this._createRole.parent) {
    //   this._createRole.parent.removeChild(this._createRole);
    //   this._createRole.stopBackgroundMusic();
    //   this._createRole = null;
    // }
    return;
  }

  private onRoleProgressHandler(
    arg1: Object /* flash.events.ProgressEvent */
  ): void {
    // GameLoadBar.instance.setProgress(PreloaderConfig.LOAD_CREATE_ROLE, arg1.bytesLoaded, arg1.bytesTotal);
    return;
  }

  private submitFun(arg1: Object): void {
    this.sendCreateRole(arg1);
    return;
  }

  private sendCreateRole(arg1: any): void {
    var loc1 = new SFirstRole();
    loc1.camp = arg1.camp;
    loc1.sex = arg1.sex;
    loc1.name = arg1.name;
    loc1.career = ECareer._ECareerNewPlayer;
    loc1.server = ParamsConst.instance.server;
    loc1.platformCode = ParamsConst.instance.platformCode;
    LoginRMI.instance.loginProxy.createFirstRole_async(
      new AMI_ILogin_createFirstRole(
        this.loginSuccess,
        this.createRoleException
      ),
      loc1
    );
    return;
  }

  public get gameSession(): GameSession {
    return this._gameSession;
  }

  public set gameSession(arg1: GameSession) {
    this._gameSession = arg1;
    return;
  }

  public get slogin(): SLogin {
    return this._slogin;
  }

  public set slogin(arg1: SLogin) {
    this._slogin = arg1;
    return;
  }

  private initApp(): void {
    // if (this._isLoadedApp == false)
    // {
    //     this._isLoadedApp = true;
    //     this.baseLoader.maxReloadTimes = 30;
    //     this.baseLoader.reloadSec = 8;
    //     this.baseLoader.addEventListener(flash.events.Event.COMPLETE, this.onCompleteHandler);
    //     this.baseLoader.addEventListener(flash.events.ProgressEvent.PROGRESS, this.onProgressHandler);
    //     this.baseLoader.addEventListener(flash.events.IOErrorEvent.IO_ERROR, this.onIOErrorHandler);
    //     this.baseLoader.load(PathConst.gameUrl + "?v=" + ParamsConst.instance.flashVersion, null);
    // }
    // return;
  }

  private onCompleteHandler(arg1: Object /* flash.events.Event */): void {
    // if (PHPSender.isCreateRole)
    // {
    //     PHPSender.sendToURLByPHP(SenderType.LoadMaigGameSwfSuccess);
    // }
    // var loc1=new Object /* flash.display.Loader */();
    // loc1.loadBytes(arg1.target.bytesData as ByteArray);
    // this.rootStage.addChild(loc1);
    // return;
  }

  public static /* const */ LOGIN_SUCCESS: string = "loginSuccess";

  public /* var */ rootStage: any /* flash.display.Stage */;

  private /* var */ _gameSession!: GameSession;

  private /* var */ _slogin!: SLogin;

  public /* var */ sloginReturn!: SLoginReturn;

  private /* var */ _createRole!: any /* flash.display.MovieClip */;

  public /* var */ isLoginSuccess: boolean = false;

  private /* var */ _isLoadedApp: boolean = false;

  private /* var */ urlloader: any /* flash.net.URLLoader */;

  private static /* var */ _instance: PreLoginProxy;

  private /* var */ baseLoader: any;
}
